<template>
  <div class="search-college">
    <div class="header">
      <img @click="goBack" class="back-arrow" :src="backArrow" alt="" />
      <SchoolSearchBox
        @upDateMatchName="upDateMatchName"
        :matchName="matchName"
      />
    </div>
    <filterMenu
      @updateProvince="updateProvince"
      @updateCollegeType="updateCollegeType"
      @updateSchoolFeature="updateSchoolFeature"
      @updateSchoolNature="updateSchoolNature"
      @updateLevelName="updateLevelName"
    />
    <div
      class="school-container"
      ref="schoolContainer"
      @scroll="debouncedCheckScrollBottom"
      v-if="schoolList.length > 0 || isLoading"
    >
      <schoolCard
        :detail="item"
        v-for="(item, index) in schoolList"
        :key="index"
      />
      <div class="loading" v-if="isLoading">加载中...</div>
    </div>
    <div class="empty" v-else>
      <Empty />
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  onActivated,
  onDeactivated,
  defineAsyncComponent,
} from 'vue';
import { getCollegeList } from '@/api/collegeSearch';
import { previousRoute } from '@/router';
import backArrow from '@/assets/images/back_arrow.png';

const SchoolSearchBox = defineAsyncComponent(() =>
  import('@/components/SchoolSearchBox.vue')
);
const filterMenu = defineAsyncComponent(() =>
  import('./components/FilterMenu.vue')
);
const schoolCard = defineAsyncComponent(() =>
  import('./components/SchoolCard.vue')
);
const Empty = defineAsyncComponent(() => import('@/components/Empty.vue'));

import antiShake from '@/utils/antiShake.js';

import { useRoute, useRouter } from 'vue-router'; // 导入路由

defineOptions({
  name: 'SearchCollege',
});
const router = useRouter();
const route = useRoute();
const goBack = () => {
  router.go(-1);
};

const schoolContainer = ref(null);

const schoolList = ref([]);
const pageNum = ref(1);
const pageSums = ref(100);
const matchName = ref(''); // 院校名称
const isLoading = ref(false);
const getCollegeListFn = async () => {
  isLoading.value = true;
  let params = {
    pageSize: 10,
    pageNo: pageNum.value,
    dualClassName: dualClassName.value,
    natureName: natureName.value,
    collegeType: collegeType.value,
    levelName: levelName.value,
    regionIdList: regionIdList.value,
    matchName: matchName.value,
  };
  if (pageSums.value >= pageNum.value) {
    const res = await getCollegeList(params);
    isLoading.value = false;
    if (res.code == 200) {
      pageSums.value = res.pageparam.pages;

      if (pageSums.value > pageNum.value) {
        pageNum.value += 1;
      }

      if (pageSums.value == 0 || pageSums.value == 1) {
        pageSums.value = 100;
      }

      if (pageNum.value == 1) {
        schoolList.value = res.data;
      } else {
        schoolList.value = [...schoolList.value, ...res.data];
        if (pageSums.value == pageNum.value && res.data.length < 10) {
          pageNum.value += 1;
        }
      }
    }
  }
};

// 检查是否滚动到底部
const checkScrollBottom = () => {
  const container = schoolContainer.value;
  if (container) {
    const { scrollTop, scrollHeight, clientHeight } = container;
    // 当滚动到底部时触发通知
    if (scrollTop + clientHeight >= scrollHeight - 10) {
      getCollegeListFn();
    }
  }
};

const debouncedCheckScrollBottom = antiShake(checkScrollBottom, 300);
const regionIdList = ref('');
const clearSchoolList = () => {
  pageNum.value = 1; // 重置页码为 1
  schoolList.value = []; // 清空当前列表数据
};
const updateProvince = (newProvince) => {
  regionIdList.value = newProvince;
  clearSchoolList();
  getCollegeListFn();
};
const collegeType = ref('');
const updateCollegeType = (newCollegeType) => {
  collegeType.value = newCollegeType;
  clearSchoolList();
  getCollegeListFn();
};
const dualClassName = ref(''); // 院校特色
const updateSchoolFeature = (newSchoolFeature) => {
  dualClassName.value = newSchoolFeature;
  clearSchoolList();
  getCollegeListFn();
};
const natureName = ref(''); // 院校性质
const updateSchoolNature = (newSchoolNature) => {
  natureName.value = newSchoolNature;
  clearSchoolList();
  getCollegeListFn();
};
const levelName = ref(''); // 本科专科
const updateLevelName = (newLevelName) => {
  levelName.value = newLevelName;
  clearSchoolList();
  getCollegeListFn();
};
const upDateMatchName = (newMatchName) => {
  matchName.value = newMatchName; // 更新 matchName 的值
  clearSchoolList();
  getCollegeListFn();
};

onMounted(() => {
  if (route.query.matchName) {
    matchName.value = route.query.matchName; // 更新 matchName 的值
  }
  // 确保在滚动事件监听中使用防抖后的函数
  if (schoolContainer.value) {
    schoolContainer.value.addEventListener(
      'scroll',
      debouncedCheckScrollBottom
    );
  }
});
onUnmounted(() => {
  if (schoolContainer.value) {
    schoolContainer.value.removeEventListener('scroll', checkScrollBottom);
  }
});
onActivated(() => {
  if (previousRoute?.name == 'Home') {
    dualClassName.value = '';
    natureName.value = '';
    collegeType.value = '';
    levelName.value = '';
    regionIdList.value = '';
    matchName.value = '';
    clearSchoolList();
  }
  if (route.query.matchName) {
    matchName.value = route.query.matchName; // 更新 matchName 的值
  } else {
    matchName.value = ''; // 更新 matchName 的值
  }
  getCollegeListFn();
  // 确保在滚动事件监听中使用防抖后的函数
  if (schoolContainer.value) {
    schoolContainer.value.addEventListener(
      'scroll',
      debouncedCheckScrollBottom
    );
  }
});
onDeactivated(() => {
  // 组件被停用时执行的代码
  if (schoolContainer.value) {
    schoolContainer.value.removeEventListener('scroll', checkScrollBottom);
  }
});
</script>

<style lang="scss" scoped>
.search-college {
  background: linear-gradient(180deg, #e8f9ff 0%, #f4f6f8 100%);
  padding: 48px 60px 0 60px;
  box-sizing: border-box;
  .icon {
    width: 24px;
    height: 24px;
  }
  .header {
    padding: 30px 0px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .back-arrow {
      width: 48px;
      height: 48px;
      position: absolute;
      left: 30px;
    }
  }
  .school-container {
    height: calc(100vh - 352px);
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-auto-rows: minmax(193px, auto);
    gap: 16px;
    overflow-y: scroll;
    padding-bottom: 48px;
    margin-top: 28px;
    box-sizing: border-box;
    /* 隐藏所有浏览器滚动条 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE/Edge */
    &::-webkit-scrollbar {
      display: none;
    } /* Chrome/Safari/Opera */
    .loading {
      grid-column: 1 / -1;
      width: 100%;
      text-align: center;
      font-size: 24px;
      color: #666666;
      padding: 0 0 40px 0;
    }
  }
  .empty {
    height: 780px;
  }
}
</style>
